package com.lvan.schedule.task;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Schedule Handler
 */
@Component
public class CronTaskRegistrar implements DisposableBean {

    private final Map<Runnable, ScheduledTask> scheduledTaskMap = new ConcurrentHashMap<>(10);

    @Autowired
    private TaskScheduler taskScheduler;

    public TaskScheduler getTaskScheduler() {
        return this.taskScheduler;
    }

    /**
     * add task
     *
     * @param runnable Runnable
     * @param cronExp  Cron
     * @return boolean
     */
    public boolean addCronTask(Runnable runnable, String cronExp) {
        return addCronTask(new CronTask(runnable, cronExp));
    }

    /**
     * add task
     *
     * @param cronTask CronTask
     * @return boolean
     */
    public boolean addCronTask(CronTask cronTask) {
        if (cronTask != null) {
            Runnable taskRunnable = cronTask.getRunnable();
            if (this.scheduledTaskMap.containsKey(taskRunnable)) {
                removeCronTask(taskRunnable);
            }
            this.scheduledTaskMap.put(taskRunnable, scheduleCronTask(cronTask));
            return true;
        }
        return false;
    }

    /**
     * remove task
     *
     * @param runnable Runnable
     * @return boolean
     */
    public boolean removeCronTask(Runnable runnable) {
        ScheduledTask scheduledTask = this.scheduledTaskMap.remove(runnable);
        if (scheduledTask != null) {
            return scheduledTask.cancel();
        }
        return false;
    }

    public ScheduledTask scheduleCronTask(CronTask cronTask) {
        ScheduledTask scheduledTask = new ScheduledTask();
        scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        return scheduledTask;
    }

    @Override
    public void destroy() {
        for (ScheduledTask task : this.scheduledTaskMap.values()) {
            task.cancel();
        }
        this.scheduledTaskMap.clear();
    }
}
